#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template

from django.utils import simplejson
from model import *

consumer_key = "j7VcMB4Kzdke8FEzdPpTkw" 
consumer_secret = "Le5eCCszXBzZRklyOZxinQyZolVBeYZel8wIUyv6T8"


class MainPage(webapp.RequestHandler):
    """ Renders the main template."""
    def get(self):
        template_values = { 'title':'JCard+', }
        path = os.path.join(os.path.dirname(__file__), "index.html")
        self.putTestData()
        test = getLatest()
        #5self.response.out.write(test)
        self.response.out.write(template.render(path, template_values))

    def putTestData(self):
        msg = UserMessage(user='u',amount=1.01,location='SJ'); msg.put();
        msg = UserMessage(user='u',amount=2.01,location='SF'); msg.put();
        msg = UserMessage(user='u',amount=3.01,location='Sea'); msg.put();
        msg = UserMessage(user='u',amount=4.01,location='NY'); msg.put();
        msg = UserMessage(user='u',amount=4.01,location='LA'); msg.put();
        msg = UserMessage(user='u',amount=4.01,location='C1'); msg.put();
        msg = UserMessage(user='u',amount=4.01,location='C2'); msg.put();
        msg = UserMessage(user='u',amount=4.01,location='C3'); msg.put();

class LatestHandler(webapp.RequestHandler):
    """ Renders the main template."""
    def loadStories(self):
        stories = getLatest()
        return stories
    
    def get(self):
        self.response.out.write(simplejson.dumps(self.loadStories()))        
        
class RPCHandler(webapp.RequestHandler):
    """ Allows the functions defined in the RPCMethods class to be RPCed."""
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()

    def loadStories(self):
        stories = getLatest()

##        story1 = {}
##        story1['post_date'] = "Aug 11, 2011"
##        story1['user_name'] = "googlehackethon"
##        story1['amount'] = 34.09
##        story1['location'] = "Mountain View, CA"
##        story1['story'] = "Very touching thing..."
##        stories.append(story1)
##
##        story2 = {}
##        story2['post_date'] = "Aug 09, 2011"
##        story2['user_name'] = "anothercoffee"
##        story2['amount'] = 19.35
##        story2['location'] = "San Francisco, CA"
##        story2['story'] = "Crazy coffee..."
##        stories.append(story2)
        return stories

    def get(self):
        func = None

        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
                return
            else:
                func = getattr(self.methods, action, None)

        if not func:
            self.error(404) # file not found
            return

        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break

        self.response.out.write(simplejson.dumps(self.loadStories()))


class RPCMethods:
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """

    def Add(self, *args):
        # The JSON encoding may have encoded integers as strings.
        # Be sure to convert args to any mandatory type(s).
        ints = [int(arg) for arg in args]
        return sum(ints)

def main():
    app = webapp.WSGIApplication([
        ('/', MainPage),
        ('/rpc', RPCHandler),
        ('/latest', LatestHandler),
        ], debug=True)
    util.run_wsgi_app(app)

if __name__ == '__main__':
    main()
